$(function () {
  const form = layui.form;
  const layer = layui.layer;

  $("#link_reg").on("click", function () {
    $(".login-box").hide();
    $(".reg-box").show();
  });

  $("#link_login").on("click", function () {
    $(".login-box").show();
    $(".reg-box").hide();
  });

  //验证规则
  form.verify({
    pass: [/^[\S]{6,12}$/, "密码必须6到12位，且不能出现空格"],
    password: function (value) {
      if ($("#ipter").val() !== value) {
        return "两次密码不一致！";
      }
    },
  });

  $("#form-box").on("submit", function (e) {
    e.preventDefault();
    const username = $("#username").val().trim();
    const password = $(".password").val().trim();
    $.ajax({
      method: "post",
      url: "/api/reguser",
      data: {
        username,
        password,
      },
      success: function (res) {
        console.log(res);
        if (res.status !== 0) {
          return layer.msg(res.message);
        }
        layer.msg(res.message);
        $("#link_login").click();
      },
    });
  });

  $("#form-login").on("submit", function (e) {
    e.preventDefault();
    $.ajax({
      method: "post",
      url: "/api/login",
      data: $("#form-login").serialize(),
      success: function (res) {
        console.log(res);
        if (res.status !== 0) {
          return layer.msg(res.message);
        }
        layer.msg(res.message);
        localStorage.setItem('token-DSJ',res.token)
        location.href = '/index.html'
      },
    });
  });
});
